/*
 * @Author: jingfuu@163.com
 * @Date: 2024-11-14 15:23:19
 * @LastEditTime: 2024-11-14 16:07:07
 * @Description: file content
 */
import { Injectable } from '@nestjs/common';
import * as nodemailer from 'nodemailer';
import * as ejs from 'ejs';
import * as fs from 'fs';
import * as path from 'path';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class MailService {
  private transporter;

  constructor(private configService: ConfigService) {
    this.transporter = nodemailer.createTransport({
      host: 'smtp.163.com',
      port: 465,
      secure: true, // 使用 SSL
      auth: {
        user: configService.get('MAIL_USER'), // 你的邮箱地址
        pass: configService.get('MAIL_PASSWORD'), // 你的邮箱密码或应用专用密码
      },
    });
  }

  async sendMail(
    to: string,
    subject: string,
    templatePath: string,
    context: object,
  ): Promise<void> {
    const source = fs.readFileSync(path.join(__dirname, templatePath), 'utf8');
    const html = await ejs.render(source, context);

    const mailOptions = {
      from: this.configService.get('MAIL_USER'),
      to,
      subject,
      html,
    };

    await this.transporter.sendMail(mailOptions);
  }
}
